package gwt.immunology.client.components;

import static gwt.immunology.shared.utils.ImmunologyUtils.DD_MM_YYYY;

import java.util.Date;

import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.datepicker.client.DateBox;
    
public class DateBoxEx extends DateBox {
    
    public DatePickerEx datePicker;
    private int defaultYear;
    private int defaultMonth = Integer.valueOf(DateTimeFormat.getFormat("M").format(new Date())) - 1;
    private static DateTimeFormat dateFormatter = DateTimeFormat.getFormat(DD_MM_YYYY);

    public DateBoxEx(final DatePickerEx datePicker) {
        super(datePicker, null, new DefaultFormat(dateFormatter));
        this.datePicker = datePicker;
        defaultYear = datePicker.monthSelector.yearsListBox.getItemCount() - 1;
        
        this.getTextBox().addFocusHandler(new FocusHandler() {
      	ListBox yearsListBox = datePicker.monthSelector.yearsListBox;
      	ListBox monthsListBox = datePicker.monthSelector.monthsListBox;
			
			@Override
			public void onFocus(FocusEvent event) {
				if(getTextBox().getText().trim().isEmpty()) {
					reset();
				} else {
					Date date = dateFormatter.parse(getTextBox().getText());
					Integer monthIndex = Integer.valueOf(DateTimeFormat.getFormat("M").format(date)) - 1;
					Integer yearIndex = Integer.valueOf(DateTimeFormat.getFormat("y").format(date));
					monthsListBox.setSelectedIndex(monthIndex);
					for (int i = 0; i < yearsListBox.getItemCount(); i++) {
						if(yearIndex.intValue() == Integer.valueOf(yearsListBox.getItemText(i)).intValue()) {
							yearsListBox.setSelectedIndex(i);
						}
					}
					datePicker.monthSelector.olderSelectedMonth = monthIndex;
			        datePicker.monthSelector.olderSelectedYear = yearIndex;
				}
			}
		});
    }
    
    @Override
    public DatePickerEx getDatePicker() {
        return this.datePicker;
    }
    
    public void reset() {
        MonthAndYearSelector monthSelector = this.datePicker.monthSelector;
        ListBox yearsListBox = monthSelector.yearsListBox;
		ListBox monthsListBox = monthSelector.monthsListBox;
		monthsListBox.setSelectedIndex(defaultMonth);
		yearsListBox.setSelectedIndex(defaultYear);
        monthSelector.olderSelectedMonth = defaultMonth;
        monthSelector.olderSelectedYear = Integer.valueOf(yearsListBox.getItemText(defaultYear));
        this.setValue(null);
    }
}
